# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: fengyang, donggu

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def _contract_type_to_expiry(contract_type):
  if contract_type == 'CURRENT_QUARTER':
    return 'QUARTER'
  elif contract_type == 'NEXT_QUARTER':
    return 'NEXT_QUARTER'
  elif contract_type == 'PERPETUAL':
    return 'PERPETUAL'
  elif contract_type in (
      'CURRENT_QUARTER DELIVERING', 'NEXT_QUARTER DELIVERING', 'PERPETUAL DELIVERING'):
    return None
  else:
    raise ValueError(contract_type)


def generate():
  mea = 'Futures.Binance.v1-delivery'
  me = 'Futures.Binance'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get("https://dapi.binance.com/dapi/v1/exchangeInfo").json()['symbols']

  pis = []
  for info in data:
    if info['contractStatus'] not in ('TRADING', 'DELIVERING'):
      continue

    native_symbol = info['symbol']
    native_base = info['baseAsset']
    native_quote = info['quoteAsset']
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    contract_type = _contract_type_to_expiry(info['contractType'])
    if contract_type is None:
      continue
    symbol = "%s-%s.%s" % (base, quote, contract_type)
    contract_value = info['contractSize']

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        contract_value=contract_value,
        is_inverse=True,
        price_ticksize=float(
            next(filter['tickSize']
                 for filter in info['filters']
                 if filter['filterType'] == 'PRICE_FILTER')),
        qty_ticksize=float(
            next(filter['stepSize']
                 for filter in info['filters']
                 if filter['filterType'] == 'LOT_SIZE')),
    )

    pi = {**default.product_info(me, symbol), **pi}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
